#!/usr/bin/env php
<?php

function read_sql_file(string $file)
{
    $comment_regex = '#(?<!:)//.*|/\*(\s|.)*?\*/|--[^\n]+#';
    $lines = explode("\n", preg_replace($comment_regex, '', co::readFile($file)));
    $init_sql = [];
    $multi = false;
    foreach ($lines as $index => $line) {
        if (strlen($line) === 0) {
            continue;
        }
        if (substr($line, -1, 1) !== ';') {
            if (!$multi) {
                $multi = true;
                goto _new_line;
            } else {
                _append:
                $end_line = &$init_sql[count($init_sql) - 1];
                $end_line = $end_line . $line . "\n";
            }
        } else {
            if ($multi) {
                $multi = false;
                goto _append;
            } else {
                $multi = false;
                _new_line:
                $init_sql[] = "{$line}";
            }
        }
    }

    return $init_sql;
}

// 解析命令行参数
$options = getopt('', ['mysql', 'firebird', 'odbc-mysql', 'help']);

// 显示帮助信息
if (isset($options['help'])) {
    echo "Usage: php init [options]\n";
    echo "Options:\n";
    echo "  --mysql      init MySQL database\n";
    echo "  --firebird   init Firebird database\n";
    echo "  --odbc-mysql init ODBC MySQL database\n";
    echo "  --help       Show help message\n";
    echo "default: init all databases\n";
    exit(0);
}

require __DIR__ . '/include/config.php';

$has_specific_option = isset($options['mysql']) || isset($options['firebird']) || isset($options['odbc-mysql']);
$load_mysql = !$has_specific_option || isset($options['mysql']);
$load_firebird = !$has_specific_option || isset($options['firebird']);
$load_odbc_mysql = !$has_specific_option || isset($options['odbc-mysql']);

require __DIR__ . '/swoole_ssh2/ssh2_test.inc';
if ($load_firebird) {
    require __DIR__ . '/swoole_pdo_firebird/pdo_firebird.inc';
}

Swoole\Coroutine\run(function () use ($load_mysql, $load_firebird, $load_odbc_mysql) {
    echo "[SSH2-init] Setting up SSH2 test environment...\n";

    $ssh_user = TEST_SSH2_USER ;
    $ssh_password = TEST_SSH2_PASS;

    $user_exists = trim(shell_exec("id -u $ssh_user 2>/dev/null"));
    if (empty($user_exists)) {
        echo "[SSH2-init] Creating test user: $ssh_user\n";
        exec("useradd -m $ssh_user");
        exec("echo '$ssh_user:$ssh_password' | chpasswd");

        exec("mkdir -p /home/$ssh_user/.ssh");

        echo "[SSH2-init] Copying SSH test key pair...\n";

        exec("cat " . __DIR__ . '/swoole_ssh2/testkey_ed25519.pub' . " > /home/$ssh_user/.ssh/authorized_keys");
        readfile("/home/$ssh_user/.ssh/authorized_keys");
        readfile('/etc/ssh/sshd_config');

        exec("chmod 700 /home/$ssh_user/.ssh");
        exec("chown -R $ssh_user:$ssh_user /home/$ssh_user/.ssh");
        exec("ssh -vvv -i " . __DIR__ . '/swoole_ssh2/testkey_ed25519' . " $ssh_user@localhost");

        readfile('/var/log/auth.log');

        echo "[SSH2-init] SSH2 test user setup completed\n";
    } else {
        echo "[SSH2-init] User $ssh_user already exists, skipping creation\n";
    }

    // 初始化MySQL数据库
    if ($load_mysql) {
        echo "[DB-init] initialization MySQL database...\n";
        $mysql = new mysqli();
        $connected = $mysql->connect(MYSQL_SERVER_HOST,
                MYSQL_SERVER_USER,
                MYSQL_SERVER_PWD,
                MYSQL_SERVER_DB,
                MYSQL_SERVER_PORT);
        if (!$connected) {
            echo "[DB-init] Connect failed! Error#{$mysql->connect_errno}: {$mysql->connect_error}\n";
            exit(1);
        }
        $sql_file = read_sql_file(__DIR__ . '/test.sql');
        foreach ($sql_file as $line) {
            if (!$mysql->query($line)) {
                echo "[DB-init] Failed! Error#{$mysql->errno}: {$mysql->error}\n";
                exit(1);
            }
        }
        echo "[DB-init] MySQL Done!\n";
    }

    // 初始化ODBC MySQL配置 - 独立控制
    if ($load_odbc_mysql) {
        echo "[DB-init] initialization ODBC...\n";
        echo `set -ex`;

        file_put_contents('/etc/odbcinst.ini', "[mysql]" . PHP_EOL
                . "Driver=libmaodbc.so" . PHP_EOL
                . "Description=MariaDB Connector/ODBC(Unicode)" . PHP_EOL
                . "UsageCount=1" . PHP_EOL
        );
        echo `odbcinst -q -d -n "mysql"`;

        file_put_contents('/etc/odbc.ini', "[mysql-test]" . PHP_EOL
                . "Description = MySQL test database" . PHP_EOL
                . "Trace = On" . PHP_EOL
                . "TraceFile = stderr" . PHP_EOL
                . "Driver = mysql" . PHP_EOL
                . "SERVER = " . MYSQL_SERVER_HOST . PHP_EOL
                . "USER = " . MYSQL_SERVER_USER . PHP_EOL
                . "PASSWORD =" . MYSQL_SERVER_PWD . PHP_EOL
                . "PORT = " . MYSQL_SERVER_PORT . PHP_EOL
                . "DATABASE = " . MYSQL_SERVER_DB);
        echo `odbcinst -i -d -f /etc/odbc.ini`;

        echo "[DB-init] ODBC Done!\n";
    }

    // 初始化Firebird数据库
    if ($load_firebird) {
        echo "[DB-init] initialization Firebird database...\n";
        try {
            $firebird = PdoFirebirdTest::create();
            // 创建一些基础表结构 - 使用Firebird兼容的方式
            try {
                // 尝试查询表是否存在 - 使用单引号避免PHP解析$符号
                $result = $firebird->query('SELECT 1 FROM rdb$relations WHERE rdb$relation_name = "SWOOLE_TEST"');
                if (!$result || $result->fetchColumn() === false) {
                    // 表不存在，创建表
                    $firebird->exec('CREATE TABLE swoole_test (id INTEGER PRIMARY KEY, data VARCHAR(255))');
                }
            } catch (PDOException $e) {
                // 如果查询失败，尝试直接创建表（可能是因为权限问题）
                try {
                    $firebird->exec('CREATE TABLE swoole_test (id INTEGER PRIMARY KEY, data VARCHAR(255))');
                } catch (PDOException $e2) {
                    // 如果表已存在，忽略此错误
                    if (!strpos($e2->getMessage(), 'already exists')) {
                        throw $e2;
                    }
                }
            }
            echo "[DB-init] Firebird Done!\n";
        } catch (PDOException $e) {
            echo "[DB-init] Firebird initialization failed: " . $e->getMessage() . "\n";
        }
    }
});
